package com.twu.biblioteca;

import java.io.*;
import java.util.List;
import java.util.Map;

public class Biblioteca {
    private String welcomeMessage;
    private PrintStream printStream;
    private BufferedReader bufferedReader;
    private List<LibraryBook> bookList;
    private Map<String, LibraryAction> options;

    //Default Actions
    private String LIST_BOOKS = "1";


    public Biblioteca(PrintStream printStream, String welcomeMessage, List<LibraryBook> bookList, Map<String, LibraryAction> options,
                      BufferedReader bufferedReader) {
        this.welcomeMessage = welcomeMessage;
        this.printStream = printStream;
        this.bookList = bookList;
        this.options = options;
        this.bufferedReader = bufferedReader;
    }

    public void run(){
        displayWelcomeMessage();
        options.get(LIST_BOOKS).performAction();
        displayOptions();
        try {
            executeUserChoice(getUserOptionChoice());
        } catch (IOException e) {
            printStream.println("Error Reading Input");
        }
    }

    public void displayWelcomeMessage() {
        printStream.println(welcomeMessage);
    }

    public void displayOptions() {
        for(LibraryAction option : options.values())
            printStream.println(option.toString());
    }

    public String getUserOptionChoice() throws IOException {
        return bufferedReader.readLine();
    }

    public void executeUserChoice(String userChoice) throws IOException {
        if(!isValid(userChoice)){
            printStream.println("Select a valid option!");
            getUserOptionChoice();
        }
        else{
            options.get(userChoice).performAction();
        }
    }

    private boolean isValid(String userChoice) {
        for(String validOption : options.keySet())
            if (userChoice.equals(validOption)){
                return true;
            }

        return false;
    }

    public void checkOut(LibraryBook book) {
        book.setAvailability(false);
    }
}
